/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package server;

/**
 *
 * @author kinder
 */

import java.net.*;
import java.io.*;
import java.util.StringTokenizer;
import java.util.Scanner;
import util.QueueMonitor;
import message.Message;


public class RunnableServer implements Runnable{

    private Socket socket;
    private InetAddress ip;
    private QueueMonitor monitor;
    private int port;

    public RunnableServer(Socket socket, QueueMonitor monitor)
    {
        this.socket = socket;
        this.monitor = monitor;
        this.ip = socket.getInetAddress();
        this.port = socket.getPort();
    }

    public void run()
    {
        try{
            try{

                InputStream socketInput = socket.getInputStream();
                Scanner socketInputScanner = new Scanner(socketInput);

                OutputStream socketOutput = socket.getOutputStream();
                PrintWriter socketOutputWriter = new PrintWriter(socketOutput, true);

                while(true)
                {
                    int i = 0;
                    String line = socketInputScanner.nextLine();
                    StringTokenizer st = new StringTokenizer(line, "|");
                    Message m = new Message(this, this.ip, this.port, socketOutputWriter);
                    m.setId(st.nextToken());

                    if(m.getId().equals("QUIT"))
                        break;

                    String[] vet = new String[st.countTokens()];

                    while(st.hasMoreTokens())
                    {
                        vet[i] = st.nextToken();
                        i++;
                    }
                    m.setData(vet);

                    try{
                        Thread.sleep(300);
                    }
                    catch (InterruptedException e){
                        e.printStackTrace();
                    }
                       // MessageHandlerFactory mf = new MessageHandlerFactory();
                       // MessageHandler handler = mf.getHandlerForType(m.getId());
                       // done = handler.handleMessage(m, ip, port, socketOutputWriter);
                    this.monitor.enqueue(m);

                }
                socketOutputWriter.close();

                }
                finally
                {
                    socket.close();
                }
         }
        catch(Exception e)
        {
            e.printStackTrace();
        }

    }

}
